import * as qiniu from 'qiniu-js'
import axios from "axios";
import {Constant} from "../hook/Constant.ts";
import {defineStore} from "pinia";

export let useQiniuStorage = defineStore('qiniu', {
    state: () => ({
        isUpdateStatus: Constant.DEFAULT,
        nextInfo: null,
    })
})
//回调函数
const observer = {
    next(res) {
        //上传中
        useQiniuStorage().isUpdateStatus = Constant.LOADING
        console.log('next: ', res)
        useQiniuStorage().nextInfo = res
    },
    error(err) {
        // 失败
        console.log('err: ', err)
        useQiniuStorage().isUpdateStatus = Constant.ERROR
    },
    complete(res) {
        // 上传成功后
        console.log('complete: ', res)
        useQiniuStorage().isUpdateStatus = Constant.SUCCESS
    }
}

// @ts-ignore
export function Qiniu_uploadFile(file, fileName, folder: Constant) {
    useQiniuStorage().isUpdateStatus = Constant.DEFAULT
    let fileExt = fileName.substring(fileName.lastIndexOf('.')).toLowerCase();
    //去掉0位和小数点
    let newFileName = Math.random().toString(16).slice(2) + fileExt;
    //从后端获取upToken
    console.log(folder + newFileName)
    axios.get('http://localhost:8080/user/upToken').then(async (res) => {
        // 上传文件
        const observable = qiniu.upload(file, folder + newFileName, res.data.data, {}, {})
        // @ts-ignore
        const subscription = observable.subscribe(observer) // 上传开始

        // while (true) {
        //
        //     if (useQiniuStorage().isUpdateStatus == Constant.ERROR) {
        //         console.log("取消上传")
        //         subscription.unsubscribe() // 上传取消
        //         break;
        //     } else if (useQiniuStorage().isUpdateStatus == Constant.SUCCESS) {
        //         console.log("上传成功")
        //         break;
        //     }
        //     //延迟判断
        //     console.log("在判断...")
        //     await new Promise(resolve => {
        //         setTimeout(resolve, 3000)
        //     })
        // }
    })
    return "http://rvoq00d8x.bkt.clouddn.com/" + folder + newFileName;
}

export function Qiniu_updateFile(file, fileName, folder:Constant) {
    axios.get('http://localhost:8080/user/upToken').then((res) => {
        // 上传文件
        const observable = qiniu.upload(file, folder + fileName, res.data.data, {}, {})
        // @ts-ignore
        const subscription = observable.subscribe(observer) // 上传开始
        // subscription.unsubscribe() // 上传取消
    })
    return "http://rvoq00d8x.bkt.clouddn.com/" + folder + fileName;
}



